package dnl.persistence;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author Daniel Orr
 */
public class DataConverter {

    public static final SimpleDateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss");

    public Object fromStringToDataObject(String s, SqlType sqlType) {
        switch (sqlType) {
            case VARCHAR:
            case VARCHAR2:
            case CHAR:
            case CLOB:
            case LONGNVARCHAR:
            case LONGVARCHAR:
            case NCLOB:
            case NVARCHAR:
            case NCHAR:
                return s;
            case BIGINT:
                return new BigDecimal(s);
            case DOUBLE:
                return Double.parseDouble(s);
            case FLOAT:
                return Float.parseFloat(s);
            case INTEGER:
                return Integer.parseInt(s);
            case NUMERIC:
            case NUMBER:
                return Integer.parseInt(s);
            case TIME:
            case DATE:
            case TIMESTAMP:
                try {
                    return new java.sql.Date(dateFormat.parse(s).getTime());
                } catch (ParseException e) {
                    throw new IllegalStateException(e);
                }
            default:
                throw new UnsupportedOperationException("Not supported: "+sqlType);
        }
    }

    public String fromDataObjectToString(Object obj) {
        if (obj instanceof String) {
            return (String) obj;
        }
        if (obj instanceof Date) {
            return dateFormat.format((Date)obj);
        }
        if (obj instanceof BigDecimal) {
            return obj.toString();
        }
        throw new UnsupportedOperationException(""+obj.getClass());
    }
}
